package com.lxyk.yygh.sms.controller;

import com.lxyk.yygh.common.result.Result;
import com.lxyk.yygh.sms.service.SmsService;
import com.lxyk.yygh.sms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SmsApiController
 * @Description TODO
 * @Author FJQ
 * @Date 2023/5/27 21:38
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/sms")
public class SmsApiController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public Result send(@PathVariable String phone){
        //从redis获取验证码  如果获取到了  直接返回ok
        //key  = 手机号   value = 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果redis没有
        //生成验证码  通过短信进行发送
        code = RandomUtil.getSixBitRandom();
        System.out.println("验证码为: " + code);
        //调用方法
        boolean isSend = smsService.send(phone, code);
        //生成的验证码放到redis  设置有效时间
        if (isSend){
           redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
           return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }
}
